/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package model;

import InterfaceGUI.DatabaseManagementSystem;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;

/**
 *
 * @author BinhNV_A04911
 */
public class ConectionDatabase {
    public static Conection conn = null;

    public ConectionDatabase(){

    }
    public static Conection getConection() throws IOException{
        String path = System.getProperty("user.dir") + "\\setting.properties";
        File fl = new File(path);
        if(!fl.exists()){
             JOptionPane.showMessageDialog(null, "Not file exists Setting connection database!", "Expo System Management", 2, null);
             DatabaseManagementSystem  dbms = new DatabaseManagementSystem(null, true);
             dbms.setVisible(true);
             return null;
        }
        FileInputStream fis = null;
        Properties prop = new Properties();
        try {
            fis = new FileInputStream(path);
            prop.load(fis);
        } catch (IOException ex) {
            return  null;
        }
        String instanceName = prop.getProperty("instanceName");
        String host = prop.getProperty("host");
        String databaseName = prop.getProperty("databaseName");
        String userName = prop.getProperty("username");
        String password = prop.getProperty("password");
        String port = prop.getProperty("port");
        String url = "jdbc:" + instanceName + "://" + host + ":" + port + ";DatabaseName=" + databaseName;
        try {
            Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
            
        } catch (ClassNotFoundException ex) {
           JOptionPane.showMessageDialog(null, ex.getMessage(), "Leave System Management", 2, null);
            return null;
        }
        try {
            conn = (Conection) DriverManager.getConnection(url, userName, password);
        } catch (SQLException ex) {
            JOptionPane.showMessageDialog(null, "Connection data error " + ex.getMessage(), "Leave System Management", 2, null);
            DatabaseManagementSystem  dbms = new DatabaseManagementSystem (null, true);
           dbms.setVisible(true);
            return null;
         }
        try {
            fis.close();
        } catch (IOException ex) {
            return null;
        }
        return conn;

    }
}


